import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/geomancy.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/models/base_model.dart';
import 'package:geomancy/models/record_list_model.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_list.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';
import 'package:geomancy/widgets/custom_refresh_header.dart';
import 'package:go_router/go_router.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class RecordListPage extends StatefulWidget {
  const RecordListPage({super.key});

  @override
  State<RecordListPage> createState() => _RecordListPageState();
}

class _RecordListPageState extends State<RecordListPage> {
  final RefreshController _refreshController = RefreshController();
  List<RecordItemModel> dataList = [];
  int page = 1;
  int size = 20;
  int totalPage = 1;

  @override
  void initState() {
    super.initState();
    getRecordList();
  }

  ///获取堪舆历史记录
  Future getRecordList() async {
    final result = await GeomancyAPI.getRecordList(context: context, page: CommonPage(page: page, size: size));
    page = result?.page ?? 1;
    size = result?.size ?? 10;
    totalPage = result?.totalPage ?? 1;
    List<RecordItemModel> currList;
    if (page == 1) {
      currList = result?.list ?? [];
    } else {
      currList = [...dataList, ...result?.list??[]];
    }
    setState(() {
      dataList = currList;
    });
  }

  Future<void> _loadMore() async {
    if (page < totalPage) {
      page++;
      await getRecordList();
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  ///根据type转化成文本
  String getTypeText(String type) {
    switch (type) {
      case '1':
      case '2':
        return '财位运';
      case '3':
      case '4':
        return '人缘位';
      case '5':
      case '6':
        return '文昌位';
      case '7':
        return '安康位';
      default:
        return '';
    }
  }
  CompassSource getCompassSource(String type) {
    switch (type) {
      case '1':
        return CompassSource.roomWealth;
      case '2':
        return CompassSource.stationWealth;
      case '3':
        return CompassSource.roomRelations;
      case '4':
        return CompassSource.stationRelations;
      case '5':
        return CompassSource.roomStudy;
      case '6':
        return CompassSource.stationStudy;
      case '7':
        return CompassSource.health;
      default:
        return CompassSource.roomWealth;
    }
  }

  void goRecordDetail(RecordItemModel item) {
    if (item.type == '1' || item.type == '2') {
      context.push('/wealth_result', extra: {
        "source": getCompassSource(item.type!),
        "direction": double.parse(item.deg!)
      });
    } else if (item.type == '3' || item.type == '4') {
      context.push('/relations_result', extra: {
        "source": getCompassSource(item.type!),
        "direction": double.parse(item.deg!),
        "birthday": item.birthday,
      });
    } else if (item.type == '5' || item.type == '6') {
      context.push('/study_result', extra: {
        "source": getCompassSource(item.type!),
        "direction": double.parse(item.deg!),
        "birthday": item.birthday,
      });
    } else {
      context.push('/health_result', extra: {
        "source": getCompassSource(item.type!),
        "direction": double.parse(item.deg!),
        "birthday": item.birthday,
        "sex": item.sex,
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context),
      backgroundColor: ColorStyle.pageDefaultColor,
      body: Column(
        children: [
          const CommonTitleWidget(txt: '历史记录'),
          Expanded(child: Container(
            margin: EdgeInsets.only(top: 20.w, left: Constant.PAGEPADDING.w, right: Constant.PAGEPADDING.w, bottom: 80.w),
            decoration: BoxDecoration(
              color: ColorStyle.themeLightColor,
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: dataList.isNotEmpty ? CommonListWidget(
              controller: _refreshController,
              enablePullDown: false,
              enablePullUp: true,
              onLoading: _loadMore,
              header: CustomFreshHeader(refreshController: _refreshController),
              child: ListView.builder(
                physics: const ClampingScrollPhysics(),
                itemCount: dataList.length,
                itemBuilder: (BuildContext context, int index) {
                  final item = dataList[index];
                  return GestureDetector(
                    onTap: () {
                      goRecordDetail(item);
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 35.w),
                      child: Container(
                        key: ValueKey(item.id),
                        height: 100.w,
                        alignment: Alignment.bottomLeft,
                        padding: EdgeInsets.only(bottom: 10.w),
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor)
                            )
                        ),
                        child: Row(
                          children: [
                            SizedBox(width: 100.w, child: CommonText(txt: getTypeText(item.type!))),
                            Expanded(child: CommonText(txt: item.createTime?.split(' ')[0] ?? '-')),
                            const CommonText(txt: '查看'),
                            SizedBox(width: 6.w),
                            Image.asset('assets/icons/icon_arrow_right.png', width: 10.w),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            ) : const Center(child: CommonText(txt: '暂无数据')),
          ))
        ],
      ),
    );
  }
}
